package org.shs.common.dao;

import java.util.HashMap;

/**
 * This Class is a DAO Factory which will be called by Controls service to get
 * the DAO instance.If the DAO instance is already created then it will return
 * that else it will create a new one and return it to the calling bean.
 * <br/>
 * <br/><b>Created:</b>&nbsp;&nbsp; 12-Nov-2008 00:18:31
 *
 * @author anirvan
 *
 */
public class CommonDAOFactory
{
   private static HashMap<String, IBaseDAO> hmp = new HashMap<String, IBaseDAO>();

   /**
    * Default constructor.
    */
   public CommonDAOFactory()
   {
      super();
   }

   /**
    * This method will return the class instance for the Class name provided
    * @param strClassName   Class name
    * @return  Instance of the DAO interface
    * @throws Exception   When class cannot be found or does not extend
    * 					   IBaseDAO
    */
   public static IBaseDAO getDAO(String strClassName) throws Exception
   {
      IBaseDAO daoRef = (IBaseDAO) hmp.get(strClassName);
      if (daoRef == null)
      {
         initDAO(strClassName);
      }

      return (IBaseDAO) hmp.get(strClassName);
   }

   /**
    * This method will instantiate the DAO implementation class
    * @param strClassName   The class name
    * @throws Exception   If class cannot be instantiated
    */
   private static synchronized void initDAO(String strClassName)
   throws Exception
   {
      IBaseDAO baseDAO = null;
      if (baseDAO == null)
      {
         baseDAO = (IBaseDAO) instantiateClassNamed(strClassName,
                                                    CommonDAOFactory.
                                                    class.getClassLoader());
         hmp.put(strClassName, baseDAO);
      }
   }

   /**
    * Create a new instance of a class specified by className. Use this
    * signature on common and server code
    * @param className   Name of class
    * @param cLoader   Classloader to be used
    * @return Object   An instance of the implementation class
    * @throws Exception   System/Unknown exception
    */
   public static Object instantiateClassNamed(String className,
                                              ClassLoader cLoader)
   throws Exception
   {
      try
      {
         return cLoader.loadClass(className).newInstance();
      }
      catch (IllegalAccessException ex)
      {
         throw new Exception("Illegal Exception for class -->" + className);
      }
      catch (InstantiationException ex)
      {
         throw new Exception("Instantiation Exception for class -->"
                  + className);
      }
      catch (ClassNotFoundException ex)
      {
         throw new Exception("Class not found for class -->" + className);
      }
   }

} // CommonDAOFactory